import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'sqlite_util.dart';

class MainManager with ChangeNotifier {
  static MainManager instance = MainManager();

  var history;
  final sqliteUtil = SqliteUtil();

  void init() async {
    sqliteUtil.createDb(1);
    // clearDb();
    refreshDbList();
  }

  Future queryAll() async {
    return query("select * from history");
  }

  Future query(sql) async {
    return sqliteUtil.query(sql);
  }

  void clearDb() {
    sqliteUtil.delete("DELETE FROM history");
  }

  void delete(info) async {
    await sqliteUtil.delete('DELETE FROM history WHERE id = ${info['id']}');
    refreshDbList();
  }

  void insert(info) async {
    var data = json.encode(info);
    if (history == null) {
      await sqliteUtil.insert("INSERT INTO history(id,info) VALUES(0,'$data')");
    } else {
      await sqliteUtil
          .update('UPDATE history SET info = ? WHERE id = 0', [data]);
    }
    refreshDbList();
  }

  refreshDbList() {
    queryAll().then((res) {
      if (res.length == 0) {
        insert({'id': '1', 'index': '《三字经》 第1段', 'title': '人之初，性本善。性相近，习相远。'});
        notifyListeners();
      } else {
        history = json.decode(res[0]['info']);
        notifyListeners();
      }
      // print(history);
    });
  }
}
